#include "th_ips117_i.h"
#include "ui_th_ips117_i.h"
#include <QDebug>
#include <QFileInfo>
#include <QSettings>
#include <QMessageBox>

TH_IPS117_I::TH_IPS117_I(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::TH_IPS117_I)
{
    ui->setupUi(this);
    initialize();
}

void TH_IPS117_I::initialize()
{
    this->setWindowTitle(tr("8路交流电源屏电压模块(TH-IPS117-I)测试工具"));
//    this->setFixedSize(369, 312);
    this->ui->statusBar->showMessage(tr("请连接分机！"));
    this->time.setInterval(2000);

    connect(ui->pushButton, &QPushButton::clicked, this, &TH_IPS117_I::on_pushButton);
    connect(ui->lineEdit_remoteIP, &QLineEdit::editingFinished, this, &TH_IPS117_I::on_remoteIPChanged);
    connect(&this->time, &QTimer::timeout, this, &TH_IPS117_I::on_testTimeout);
    connect(&socket, &QUdpSocket::readyRead, this, &TH_IPS117_I::on_socketReceive);
    connect(ui->spinBox, SIGNAL(valueChanged(int)), this, SLOT(on_spinBoxChanged(int)));
    connect(ui->checkBox, &QCheckBox::toggled, this, &TH_IPS117_I::on_AutoTest);
    readConfig();
    loadName();
}

TH_IPS117_I::~TH_IPS117_I()
{
    delete ui;
}

TH_IPS117_I::DataFrame TH_IPS117_I::toDataFrame(QByteArray array)
{
    TH_IPS117_I::DataFrame ret;

    if(array.size() != 16) {
        qDebug() << "8路交流电源屏电压采集模块数据不完整：" << array.data();
        return ret;
    }

    qint16 *pdata;
    pdata = (qint16 *)array.data();

    ret.voltage1  = (float) * pdata * (300.0 / 10000);
    ret.voltage2  = (float) * (pdata + 1) * (300.0 / 10000);
    ret.voltage3  = (float) * (pdata + 2) * (300.0 / 10000);
    ret.voltage4  = (float) * (pdata + 3) * (300.0 / 10000);
    ret.voltage5  = (float) * (pdata + 4) * (300.0 / 10000);
    ret.voltage6  = (float) * (pdata + 5) * (300.0 / 10000);
    ret.voltage7  = (float) * (pdata + 6) * (300.0 / 10000);
    ret.voltage8  = (float) * (pdata + 7) * (300.0 / 10000);

    return ret;
}

void TH_IPS117_I::setDisplay(DataFrame data)
{
    ui->lineEdit_1->setText(QString::number(data.voltage1, 'f', 2));
    ui->lineEdit_2->setText(QString::number(data.voltage2, 'f', 2));
    ui->lineEdit_3->setText(QString::number(data.voltage3, 'f', 2));
    ui->lineEdit_4->setText(QString::number(data.voltage4, 'f', 2));
    ui->lineEdit_5->setText(QString::number(data.voltage5, 'f', 2));
    ui->lineEdit_6->setText(QString::number(data.voltage6, 'f', 2));
    ui->lineEdit_7->setText(QString::number(data.voltage7, 'f', 2));
    ui->lineEdit_8->setText(QString::number(data.voltage8, 'f', 2));
}

void TH_IPS117_I::clearDisplay()
{
    ui->spinBox->setRange(0, 0);

    ui->lineEdit_1->clear();
    ui->lineEdit_2->clear();
    ui->lineEdit_3->clear();
    ui->lineEdit_4->clear();
    ui->lineEdit_5->clear();
    ui->lineEdit_6->clear();
    ui->lineEdit_7->clear();
    ui->lineEdit_8->clear();
}

void TH_IPS117_I::readConfig()
{
    QFileInfo file("./cfg.ini");

    if(file.exists()) {
        QSettings *read = new QSettings("cfg.ini", QSettings::IniFormat);
        ui->lineEdit_remoteIP->setText(read->value("UDP/RemoteIP").toString());
        ui->spinBox_remotePort->setValue(read->value("UDP/RemotePort").toInt());
        bool temp = read->value("UDP/FixedLocalPort").toBool();
        ui->checkBox_localPort->setChecked(temp);
        ui->spinBox_localPort->setValue(read->value("UDP/LocalPort").toInt());

        delete read;
    } else {
        qDebug() << "cfg.ini 文件不存在！";
    }
}

void TH_IPS117_I::writeConfig()
{

    QSettings *writer = new QSettings("cfg.ini", QSettings::IniFormat);
    writer->setValue("UDP/RemoteIP", ui->lineEdit_remoteIP->text());
    writer->setValue("UDP/RemotePort", ui->spinBox_remotePort->value());

    if(ui->checkBox_localPort->isChecked()) {
        writer->setValue("UDP/FixedLocalPort", true);
    } else {
        writer->setValue("UDP/FixedLocalPort", false);
    }

    writer->setValue("UDP/LocalPort", ui->spinBox_localPort->value());

    delete writer;
}

void TH_IPS117_I::on_pushButton()
{
    if(socket.isValid()) {
        ui->checkBox->setChecked(false);
        this->time.stop();
        clearDisplay();
        socket.close();
        ui->groupBox->setEnabled(false);
        ui->lineEdit_remoteIP->setEnabled(true);
        ui->spinBox_remotePort->setEnabled(true);
        ui->checkBox_localPort->setEnabled(true);
        ui->spinBox_localPort->setEnabled(true);
        ui->pushButton->setText(tr("连接分机"));
        ui->statusBar->showMessage(tr("请重新连接分机!"));
    } else {
        if(ui->checkBox_localPort->isChecked()) {
            this->socket.bind(ui->spinBox_localPort->value());
        }

        this->socket.connectToHost(QHostAddress(ui->lineEdit_remoteIP->text()), ui->spinBox_remotePort->value());

        if(socket.isValid()) {
            writeConfig();
            ui->groupBox->setEnabled(true);
            ui->lineEdit_remoteIP->setEnabled(false);
            ui->spinBox_remotePort->setEnabled(false);
            ui->checkBox_localPort->setEnabled(false);
            ui->spinBox_localPort->setEnabled(false);
            ui->pushButton->setText(tr("断开连接"));
            ui->statusBar->showMessage(tr("\"回车\"进行1次测试!"));
        }
    }

}

void TH_IPS117_I::on_remoteIPChanged()
{
    QHostAddress ip(ui->lineEdit_remoteIP->text());

    if(ip.toString() != NULL) {
        this->ui->lineEdit_remoteIP->setText(ip.toString());
    } else {
        QMessageBox::warning(this, tr("错误："), tr("输入的分机IP地址有误，请重新输入!"), QMessageBox::Ok);
        ui->lineEdit_remoteIP->setFocus();
    }
}

void TH_IPS117_I::startOneTest()
{
    qDebug() << "开始一次手动测试……";
    this->ui->statusBar->showMessage(tr("正在测试……"));
    char code[2];
    code[0] = 0x01;
    code[1] = 0xBD;
    socket.writeDatagram(code, 2, QHostAddress(ui->lineEdit_remoteIP->text()), ui->spinBox_remotePort->value());
    qDebug() << "开起定时器……";
    this->time.start();
}

void TH_IPS117_I::on_testTimeout()
{
    qDebug() << "分机超时未响应……";
    this->statusBar()->showMessage(tr("超时未响应……请确认ip及端口号是否正确,分机是否在正常工作！"));
    this->time.stop();
    this->arrayData.clear();
    ui->spinBox->setRange(0, 0);
    ui->spinBox->setValue(0);

    if(ui->checkBox->isChecked()) {
        startOneTest();
    }
}

void TH_IPS117_I::keyPressEvent(QKeyEvent *event)
{
    if(!socket.isValid()) return;

    if(ui->checkBox->isChecked()) return;

    if(event->key() == Qt::Key_Return && !time.isActive()) {
        startOneTest();
    }
}

void TH_IPS117_I::on_spinBoxChanged(int arg)
{
    if(this->arrayData.isEmpty()) {
        ui->spinBox->setRange(0, 0);
        clearDisplay();
    } else {
        DataFrame dat = this->toDataFrame((arrayData.mid((arg - 1) * 16, 16)));
        setDisplay(dat);
    }

    setName(arg * 8 - 7);
}

void TH_IPS117_I::on_socketReceive()
{
    qDebug() << "收到数据……";
    QByteArray ret;
    ret.resize(socket.pendingDatagramSize());
    QHostAddress ip;
    quint16 port;

    socket.readDatagram(ret.data(), socket.pendingDatagramSize(), &ip, &port);
//    qDebug() << ret;

    if(ret.isEmpty()) return;

    if(ret.at(0) != 0x00 || ret[1] != (char)0xBD) {
        ui->statusBar->showMessage(tr("非8路交流电源屏电压数据包……"));
        return;
    }

//    quint16 len = (ret[3] << 8) + ret[2];
    quint16 *plen = (quint16*)ret.data();
    quint16 len = *(plen + 1);

    if(len == 0x00) {
        ui->statusBar->showMessage(tr("分机未配置8路交流电源屏电压模块,请检查分机配置！"));
        this->time.stop();
        return;
    }

    if(len * 2 != ret.size() - 4) {
        ui->statusBar->showMessage(tr("非完整的8路交流电源屏电压数据包……"));
        return;
    }

    this->arrayData = ret.mid(4);
    ui->spinBox->setRange(1, len / 8);
    ui->statusBar->showMessage(tr("测试完成！"));
    DataFrame dat = toDataFrame(arrayData.mid((ui->spinBox->value() - 1) * 16, 16));
    setDisplay(dat);

    if(ui->checkBox->isChecked()) {
        startOneTest();
    } else {
        this->time.stop();
    }
}

void TH_IPS117_I::on_AutoTest()
{
    startOneTest();
}

void TH_IPS117_I::loadName()
{
    QFileInfo file("DataName.ini");

    if(file.exists()) {
        QSettings *read = new QSettings("DataName.ini", QSettings::IniFormat);
        read->setIniCodec("GBK");
        read->beginGroup("TH-IPS117-I");
        foreach(QString item, read->childKeys()) {
            this->name.insert(item.toInt(), read->value(item).toString());
        }
//        qDebug() << this->name;
    } else {
        qDebug() << "DataName.ini配置文件不存在！";
    }
}

void TH_IPS117_I::setName(unsigned int arg)
{
    if(0 == arg) {
        ui->label_1->setText("第1路:");
        ui->label_2->setText("第2路:");
        ui->label_3->setText("第3路:");
        ui->label_4->setText("第4路:");
        ui->label_5->setText("第5路:");
        ui->label_6->setText("第6路:");
        ui->label_7->setText("第7路:");
        ui->label_8->setText("第8路:");
    } else {
        if(this->name.contains(arg)) {
            ui->label_1->setText(this->name.value(arg) + ":");
        } else {
            ui->label_1->setText("第1路:");
        }

        if(this->name.contains(arg + 1)) {
            ui->label_2->setText(this->name.value(arg + 1) + ":");
        } else {
            ui->label_2->setText("第2路:");
        }

        if(this->name.contains(arg + 2)) {
            ui->label_3->setText(this->name.value(arg + 2) + ":");
        } else {
            ui->label_3->setText("第3路:");
        }

        if(this->name.contains(arg + 3)) {
            ui->label_4->setText(this->name.value(arg + 3) + ":");
        } else {
            ui->label_4->setText("第4路:");
        }
        if(this->name.contains(arg + 4)) {
            ui->label_5->setText(this->name.value(arg + 4) + ":");
        } else {
            ui->label_5->setText("第5路:");
        }
        if(this->name.contains(arg + 5)) {
            ui->label_6->setText(this->name.value(arg + 5) + ":");
        } else {
            ui->label_6->setText("第6路:");
        }
        if(this->name.contains(arg + 6)) {
            ui->label_7->setText(this->name.value(arg + 6) + ":");
        } else {
            ui->label_7->setText("第7路:");
        }
        if(this->name.contains(arg + 7)) {
            ui->label_8->setText(this->name.value(arg + 7) + ":");
        } else {
            ui->label_8->setText("第8路:");
        }
    }
}
